﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Fighter.Fights.ModuleData;
using Fighter.Masters.ModuleData;
using ApplicationLibrary.ExtendedControls;
using ApplicationLibrary.SqlConnector;
using ApplicationLibrary;
using WeifenLuo.WinFormsUI;

namespace Fighter.Fights.Forms
{
    public partial class CallOfDuty : WeifenLuo.WinFormsUI.Docking.DockContent
    {
        private RRRegistrated rRRegistrated;
        private bool inedit;
        private int lastPresentEdit = 0;
        private int lastAbsentEdit = 0;
        private DataGridViewRow curRow;
        private EnumsManager<Gender> eGenderManager = new EnumsManager<Gender>();
        private EnumsManager<Belts> eBeltsManager = new EnumsManager<Belts>();
        private DRAthlete dRAthlete;
        private DRRegistration dRRegistration;
        private RRFight rRFight;

        bool InEdit
        {
            set
            {
                dgwAbsent.Enabled = !value;
                dgwPresent.Enabled = !value;
                splitContainer3.Enabled = value;
                tsbEdit.Enabled = !value;
                tsbSave.Enabled = value;
                tsbRefresh.Enabled = !value;
                inedit = value;
            }
            get { return inedit; }
        }

        public CallOfDuty()
        {
            InitializeComponent();
            InitializeAuxData();
        }

        private void InitializeAuxData()
        {
            rRRegistrated = new RRRegistrated();
            dRAthlete = new DRAthlete(true);
            dRRegistration = new DRRegistration(true);
            rRFight = new RRFight();

            eGenderManager = new EnumsManager<Gender>(cbbGender);
            eBeltsManager = new EnumsManager<Belts>(cbbBelt);
        }

        protected override void OnShown(EventArgs e)
        {
            base.OnShown(e);

            RefreshData();
            InEdit = false;
        }

        private void RefreshData()
        {
            dgwPresent.Rows.Clear();
            if (rRRegistrated.Find(true))
            {
                for (int t = 0; t < rRRegistrated.Count; t++)
                {
                    string club = rRRegistrated.GetValue<string>(FG_Club.Club, t);
                    string mail = rRRegistrated.GetValue<string>(FG_Club.Mail, t);
                    int athleteID = rRRegistrated.GetValue<int>(FG_Athlete.ID, t);
                    string athleteName = rRRegistrated.GetValue<string>(FG_Athlete.FirstName, t);

                    dgwPresent.Rows.Add(club, athleteName, mail, athleteID);
                }
            }

            dgwAbsent.Rows.Clear();
            if (rRRegistrated.Find(false))
            {
                for (int t = 0; t < rRRegistrated.Count; t++)
                {
                    string club = rRRegistrated.GetValue<string>(FG_Club.Club,t);
                    string mail = rRRegistrated.GetValue<string>(FG_Club.Mail, t);
                    int athleteID = rRRegistrated.GetValue<int>(FG_Athlete.ID, t);
                    string athleteName = rRRegistrated.GetValue<string>(FG_Athlete.FirstName, t);

                    dgwAbsent.Rows.Add(club, athleteName, mail, athleteID);
                }
            }
            if (lastAbsentEdit > 0 && lastAbsentEdit < dgwAbsent.Rows.Count)
                dgwAbsent.CurrentCell = dgwAbsent.Rows[lastAbsentEdit].Cells[0];

            if (lastPresentEdit > 0 && lastPresentEdit < dgwPresent.Rows.Count)
                dgwPresent.CurrentCell = dgwPresent.Rows[lastPresentEdit].Cells[0];
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            if (InEdit)
                return;
            RefreshData();
        }

        private void dgwAbsent_Click(object sender, EventArgs e)
        {
            if (dgwAbsent.CurrentRow != null)
            {
                lastAbsentEdit = dgwAbsent.CurrentRow.Index;
                CompileControlMask(dgwAbsent.CurrentRow);
            }
        }

        private void dgwPresent_Click(object sender, EventArgs e)
        {
            if (dgwPresent.CurrentRow != null)
            {
                lastPresentEdit = dgwPresent.CurrentRow.Index;
                CompileControlMask(dgwPresent.CurrentRow);
            }
        }

        private void dgwAbsent_DoubleClick(object sender, EventArgs e)
        {
            if (dgwAbsent.CurrentRow != null)
            {
                lastAbsentEdit = dgwAbsent.CurrentRow.Index;
                CompileControlMask(dgwAbsent.CurrentRow);
                InEdit = true;
            }
        }

        private void dgwPresent_DoubleClick(object sender, EventArgs e)
        {
            if (dgwPresent.CurrentRow != null)
            {
                lastPresentEdit = dgwPresent.CurrentRow.Index;
                CompileControlMask(dgwPresent.CurrentRow);
                InEdit = true;
            }
        }


        private void tsbEdit_Click(object sender, EventArgs e)
        {
            InEdit = true;
            CheckData();
        }

        private void tsbSave_Click(object sender, EventArgs e)
        {
            if (CheckData())
            {
                Validate();
                InEdit = false;
                SaveData();
            }
        }

        private void SaveData()
        {
           // Save Athlete
            string mail = curRow.Cells[2].Value.ToString();
            int athlete = int.Parse(curRow.Cells[3].Value.ToString());
            int fight = 0;
            if (rRFight.Find())
                fight = rRFight.GetValue<int>(FG_Fight.ID);

            if (dRAthlete.Find(athlete))
            {
                dRAthlete.SetValue<string>(FG_Athlete.FirstName, txtAthlete.Text);
                dRAthlete.SetValue<int>(FG_Athlete.Belt, (int)cbbBelt.SelectedValue);
                dRAthlete.SetValue<int>(FG_Athlete.Gender, (int)cbbGender.SelectedValue);
                dRAthlete.SetValue<double>(FG_Athlete.Weight, ntbWeight.Double);
                dRAthlete.SetValue<DateTime>(FG_Athlete.BirthDay, ctbBirthday.Today);
                dRAthlete.SetValue<string>(FG_Athlete.GrapLevel, cbbGrapLevel.Text);
                dRAthlete.SetValue<int>(FG_Athlete.FContMatch, ntbFContMatch.Int);
                dRAthlete.SetValue<int>(FG_Athlete.K1RulMatch, ntbK1RulMatch.Int);
                dRAthlete.SetValue<int>(FG_Athlete.LKickMatch, ntbLKickMatch.Int);

                dRAthlete.Update();
            }

            if (dRRegistration.Find(mail, athlete, fight))
            {
                dRRegistration.SetValue<bool>(FG_Registration.Checked, ckbPresent.Checked);
                WriteCheckedListbox();
                dRRegistration.Update();
            }

            RefreshData();
        }

        private bool CheckData()
        {
            bool ok = true;
            int eta = CalculateAge(ctbBirthday.Today, GlobalInfo.CurrentDate);
            if (eta > 50)
            {
                errorProvider.SetError(ctbBirthday, string.Format(Properties.Resources.M_AgeOver, eta));
                MessageBox.Show(this, string.Format(Properties.Resources.M_AgeOver, eta), Properties.Resources.M_Warning);
                //ok = false;
            }
            else
                errorProvider.SetError(ctbBirthday, string.Empty);

            return ok;

            //if (GetValue("Grappling") && eta >= 16 && cbbGrapLevel.Text.IsEmpty())
            //{
            //    errorProvider.SetError(cbbGrapLevel, Properties.Resources.M_MissingGrapLevel);
            //    MessageBox.Show(this, Properties.Resources.M_MissingGrapLevel, Properties.Resources.M_Warning);
            //    ok = false;
            //}
            //else
            //    errorProvider.SetError(cbbGrapLevel, string.Empty);

            //if (GetValue("Full Contact") && ntbFContMatch.Int == 0)
            //{
            //    errorProvider.SetError(ntbFContMatch, Properties.Resources.M_MissingFullContact);
            //    MessageBox.Show(this, Properties.Resources.M_MissingFullContact, Properties.Resources.M_Warning);
            //    ok = false;
            //}
            //else
            //    errorProvider.SetError(ntbFContMatch, string.Empty);

            //if (GetValue("K1 Rules") && ntbK1RulMatch.Int == 0)
            //{
            //    errorProvider.SetError(ntbK1RulMatch, Properties.Resources.M_MissingK1Rules);
            //    MessageBox.Show(this, Properties.Resources.M_MissingK1Rules, Properties.Resources.M_Warning);
            //    ok = false;
            //}
            //else
            //    errorProvider.SetError(ntbK1RulMatch, string.Empty);

            //if (GetValue("Low Kick") && ntbLKickMatch.Int == 0)
            //{
            //    errorProvider.SetError(ntbLKickMatch, Properties.Resources.M_MissingLKick);
            //    MessageBox.Show(this, Properties.Resources.M_MissingLKick, Properties.Resources.M_Warning);
            //    ok = false;
            //}
            //else
            //    errorProvider.SetError(ntbLKickMatch, string.Empty);

            //if (eta >= 18 &&
            //    (GetValue("Point Fighting") || GetValue("Light Contact") || GetValue("Kick Light") || GetValue("K1 Light") || GetValue("Thai Light")) &&
            //    cbbBelt.Text.TrimAll().IsEmpty())
            //{
            //    errorProvider.SetError(cbbBelt, Properties.Resources.M_MissingBelt);
            //    MessageBox.Show(this, Properties.Resources.M_MissingBelt, Properties.Resources.M_Warning);
            //    ok = false;
            //}
            //else
            //    errorProvider.SetError(cbbBelt, string.Empty);
                
            //return ok;
        }

        private void tsbUndo_Click(object sender, EventArgs e)
        {
            InEdit = false;
        }

        private void tsbRefresh_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void CompileControlMask(DataGridViewRow curRow)
        {
            this.curRow = curRow;
            txtClub.Text = curRow.Cells[0].Value.ToString();
            txtAthlete.Text = curRow.Cells[1].Value.ToString();
            string mail = curRow.Cells[2].Value.ToString();
            int athlete = int.Parse(curRow.Cells[3].Value.ToString());
            int fight =0;
            if (rRFight.Find())
                fight = rRFight.GetValue<int>(FG_Fight.ID);

            if (dRAthlete.Find(athlete))
            {
                cbbBelt.SelectedValue = dRAthlete.GetValue<int>(FG_Athlete.Belt);
                cbbGender.SelectedValue = dRAthlete.GetValue<int>(FG_Athlete.Gender);
                ntbWeight.Double = dRAthlete.GetValue<double>(FG_Athlete.Weight);
                ctbBirthday.Today = dRAthlete.GetValue<DateTime>(FG_Athlete.BirthDay);
                cbbGrapLevel.Text = dRAthlete.GetValue<string>(FG_Athlete.GrapLevel);
                ntbFContMatch.Int = dRAthlete.GetValue<int>(FG_Athlete.FContMatch);
                ntbK1RulMatch.Int = dRAthlete.GetValue<int>(FG_Athlete.K1RulMatch);
                ntbLKickMatch.Int = dRAthlete.GetValue<int>(FG_Athlete.LKickMatch);
            }

            if (dRRegistration.Find(mail, athlete, fight))
            {
                ckbPresent.Checked = dRRegistration.GetValue<bool>(FG_Registration.Checked);
                ReadCheckedListbox();
            }
        }

        private void ReadCheckedListbox()
        {
            Read("Chauss Fight Assalto", FG_Registration.ChausLight);
            Read("Savate Assalto", FG_Registration.SavateAss);
            Read("Free Punch Light", FG_Registration.PointFight);

            Read("Light Contact",FG_Registration.LightContact);
            Read("Kick Light",FG_Registration.KickLight);
            Read("K1 Light",FG_Registration.K1Light);
            Read("Thai Light",FG_Registration.ThaiLight);
            Read("MMA Light",FG_Registration.MmaLight);
            Read("Grappling",FG_Registration.Grapling);
            Read("Chauss Fight Combat", FG_Registration.ChaussCombact);
            Read("Savate Combat", FG_Registration.SavateCombact);
            Read("Free Punch", FG_Registration.FullContact);
            Read("Low Kick", FG_Registration.LowKick);
            Read("K1 Rules", FG_Registration.K1Rules);
            Read("Thai Full Rules", FG_Registration.ThaiFull);
            Read("MMA Full Rules", FG_Registration.MMAFull);
        }

        private void WriteCheckedListbox()
        {
            Write("Chauss Fight Assalto", FG_Registration.ChausLight);
            Write("Savate Assalto", FG_Registration.SavateAss);
            Write("Free Punch Light", FG_Registration.PointFight);
            Write("Light Contact", FG_Registration.LightContact);
            Write("Kick Light", FG_Registration.KickLight);
            Write("K1 Light", FG_Registration.K1Light);
            Write("Thai Light", FG_Registration.ThaiLight);
            Write("MMA Light", FG_Registration.MmaLight);
            Write("Grappling", FG_Registration.Grapling);
            Write("Chauss Fight Combat", FG_Registration.ChaussCombact);
            Write("Savate Combat", FG_Registration.SavateCombact);
            Write("Free Punch", FG_Registration.FullContact);
            Write("Low Kick", FG_Registration.LowKick);
            Write("K1 Rules", FG_Registration.K1Rules);
            Write("Thai Full Rules", FG_Registration.ThaiFull);
            Write("MMA Full Rules", FG_Registration.MMAFull);
        }

        private void Read(string fight, iColumn column)
        {
            for (int t = 0; t < clbFghts.Items.Count;t++ )
                if (clbFghts.GetItemText(clbFghts.Items[t]) == fight)
                    clbFghts.SetItemChecked(t, dRRegistration.GetValue<bool>(column));
        }

        private void Write(string fight, iColumn column)
        {
            for (int t = 0; t < clbFghts.Items.Count; t++)
                if (clbFghts.GetItemText(clbFghts.Items[t]) == fight)
                    dRRegistration.SetValue<bool>(column, clbFghts.GetItemChecked(t));
        }

        private bool GetValue(string fight)
        {
            for (int t = 0; t < clbFghts.Items.Count; t++)
                if (clbFghts.GetItemText(clbFghts.Items[t]) == fight)
                    return clbFghts.GetItemChecked(t);

            System.Diagnostics.Debug.Assert(false);
            return true;
        }

        public int CalculateAge(DateTime birthDate, DateTime now)
        {
            int age = now.Year - birthDate.Year;
            if (now.Month < birthDate.Month || (now.Month == birthDate.Month && now.Day < birthDate.Day)) age--;
            return age;
        }

        private void dgwAbsent_SelectionChanged(object sender, EventArgs e)
        {
            if (dgwAbsent.CurrentRow != null)
            {
                lastAbsentEdit = dgwAbsent.CurrentRow.Index;
                CompileControlMask(dgwAbsent.CurrentRow);
            }
        }

        private void dgwPresent_SelectionChanged(object sender, EventArgs e)
        {
            if (dgwPresent.CurrentRow != null)
            {
                lastPresentEdit = dgwPresent.CurrentRow.Index;
                CompileControlMask(dgwPresent.CurrentRow);
            }
        }

    }
}
